"""
@ProjectName : CourseManagementSystem
@File        : DBUtils.py
@Author      : WorldWind(1772830365@qq.com)
@Address     : ChangSha - BoWeiFeng
@Date        : 2025/7/17 下午1:36
"""
import pymysql
from pymysql import cursors


# 工具类
class DataBase:
    def __init__(self):
        print(f'This is __init__ method. {self.get_class_name()} class startup')

    @staticmethod
    def opemDB(host, port, user, passwd, db):
        dbObj = pymysql.connect(host=host, port=port, user=user, passwd=passwd, db=db, charset='utf8')
        cursor = dbObj.cursor(cursors.DictCursor)
        # print('执行',dbObj,cursor)
        return dbObj, cursor

    @staticmethod
    def readAll(sql, cursor):
        cursor.execute(sql)
        record = cursor.fetchall()
        return record

    @staticmethod
    def readOne(sql, cursor):
        cursor.execute(sql)
        record = cursor.fetchone()
        return record

    @staticmethod
    def writeDB(sql, cursor):
        result = cursor.execute(sql)
        return result

    @staticmethod
    def closeDB(dbObj):
        dbObj.close()

    @classmethod
    def get_class_name(cls):
        return cls.__name__

    def __del__(self):
        print(f'This is __del__ method. The {self.get_class_name()} class has been recycled')


if __name__ == '__main__':
    dbObj, cursor = DataBase().opemDB('127.0.0.1', 3306, 'root', 'root', 'course')
    # sql = 'SELECT * FROM t_course'
    # result = DataBase().readAll(sql, cursor)
    # sql = "SELECT * FROM t_course WHERE course_name like '%原理%'"
    # result = DataBase().readOne(sql, cursor)
    sql = "INSERT INTO t_course(course_no,course_name,max_score,min_sorce) VALUES ('c001','计算机组成原理',100,60)"
    result = DataBase().writeDB(sql, cursor)
    dbObj.commit()
    print(result)
